﻿using System;
using System.IO;
using System.Web;
using up6.db.store;

namespace up6.db.utils
{
    public class WebWriter
    {
        public int cacheSize = 1048576;//1MB，默认内存块大小

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fr"></param>
        /// <param name="hr"></param>
        /// <param name="pathSvr"></param>
        /// <param name="blockSize">需要下载的大小</param>
        public void write(FileBlockReader fr,HttpResponse hr,string pathSvr,long offset, int blockSize)
        {
            // 总共需要下载的长度
            int dataToRead = blockSize;
            //每次读1MB，然后传给终端
            int buf_size = Math.Min(this.cacheSize, blockSize);
            byte[] buffer = null;
            int length=0;
            while (dataToRead > 0)
            {
                // Verify that the client is connected.
                if (hr.IsClientConnected)
                {
                    // Read the data in buffer.
                    buffer = fr.read(pathSvr, offset, buf_size);
                    length = buffer.Length;
                    if (length < 1) throw new IOException("read data error");

                    dataToRead -= length;
                    offset+=length;//
                    buf_size = dataToRead < buf_size ? dataToRead : buf_size;

                    // Write the data to the current output stream.
                    hr.OutputStream.Write(buffer, 0, length);

                    // Flush the data to the HTML output.
                    hr.Flush();
                }
                else
                {
                    //prevent infinite loop if user disconnects
                    dataToRead = -1;
                }
            }
        }
    }
}